﻿/*
* Roli Christen
* <roland.christen@hslu.ch>
* 2012
*/

// Constants for KeyHandling
var KeyConstants = { KeyUp: 38, KeyDown: 40, Return: 13 };

String.prototype.format = function() {

	// load arguments into array
	var data = Array.prototype.slice.call(arguments);

	// replace placeholder with values
	return this.replace(/\{([0-9])\}/g, function(match, group) {
		return data[parseInt(group)];
	});
};
String.prototype.endsWith = function(exp) {

	var tail = this.substring(this.length - exp.length);
	return (tail == exp);
};


// selector extension to find asp.net controls with auto client-id's
// useage: $(':asp(ID)')
$.extend($.expr[':'], {
	asp: function(obj, index, meta, stack) {

		// unknown bug
		// return jQuery(obj).attr('id') && jQuery(obj).attr('id').endsWith(meta[3]);
		var id = jQuery(obj).attr('id');
		if (!id) {
			return false;
		}
		return id.endsWith(meta[3]);

	}
});

// extension for date class
Date.prototype.format = function(formatExp) {

	// get parts
	var h = this.getHours();
	var n = this.getMinutes();
	var s = this.getSeconds();
	var y = this.getFullYear();
	var m = this.getMonth() + 1;
	var d = this.getDate();

	// prepare values
	var map = {};
	map['hh'] = h < 10 ? '0' + h : h;
	map['nn'] = n < 10 ? '0' + n : n;
	map['ss'] = s < 10 ? '0' + s : s;
	map['h'] = h;
	map['n'] = n;
	map['s'] = s;
	map['yyyy'] = y;
	map['mm'] = m < 10 ? '0' + m : m;
	map['dd'] = d < 10 ? '0' + d : d;
	map['yy'] = ('' + y).substr(2);
	map['m'] = m;
	map['d'] = d;

	// replace values
	var ret = formatExp;
	$.each(map, function(key, value) {
		ret = ret.replace(new RegExp(key, 'g'), value);
	});

	return ret;
};

// extension for array class
Array.prototype.remove = function(item) {
	var index = this.indexOf(item);
	if (index != -1) this.splice(index, 1);
};

// global function to easily create method overloading
function addMethod(object, name, fn) {
	var old = object[name];
	object[name] = function() {
		if (fn.length == arguments.length)
			return fn.apply(this, arguments);
		else if (typeof old == 'function')
			return old.apply(this, arguments);
		return false;
	};
}

// (c) <roland.christen@hslu.ch>

// extend jquery with hasAttr method
(function(jQuery) {
	jQuery.fn.hasAttr = function(name) {
		for (var i = 0, l = this.length; i < l; i++) {
			if (!!(this.attr(name) !== undefined)) {
				return true;
			}
		}
		return false;
	};
})(jQuery);

// extend jquery with change Instant function
(function(jQuery) {
	jQuery.fn.changeInstant = function(scope, callback) {
		for (var i = 0, l = this.length; i < l; i++) {
			this.on('change.{0} keypress.{0} paste.{0} textInput.{0} input.{0}'.formatEx(scope), callback);
		}
		return this;
	};
})(jQuery);
(function(jQuery) {
	jQuery.fn.changeInstantOff = function(scope) {
		for (var i = 0, l = this.length; i < l; i++) {
			this.off('change.{0} keypress.{0} paste.{0} textInput.{0} input.{0}'.formatEx(scope));
		}
		return this;
	};
})(jQuery);